import axios from 'axios'
import {appToken,baseStoreState} from '@/utils/dict'
import {$local,$pathTo} from "@/utils"
import { closeLoading, openLoading } from '@/utils/loading'
import { Notify } from 'vant'
import localHttp from '@/webServer'
const baseUrl = process.env.VUE_APP_BASE_API
const failToast = function(text){
  Notify({ 
    type: 'danger',
    color: '#ffffff',
    background: '#ff6868',
    duration: 500,
    message: text 
  });
}
const $axios = axios.create({
  timeout: 4290000
})
$axios.interceptors.request.use(
  config => {
    !(config as any).noLoading && openLoading()
    config.baseURL = process.env.VUE_APP_PC_AFTER
    const token = $local(appToken);
    if (token) {
      config.headers['Authorization'] = 'Bearer'+token // 请求头部添加token
    }
    // 请求头部添加token
    return config
  },
  error => {
    closeLoading();
    return Promise.reject(error)
  }
)
/**
 * 响应拦截器
 * 用于处理loading状态关闭、请求成功回调、响应错误处理
 */
$axios.interceptors.response.use(
  response => {
    !(response.config as any).noLoading && closeLoading()
    const status = response.status
    const code = response.data.code
    if ((status >= 200 && status < 300) || status === 304) {
      if (['0','200'].indexOf(code+'') != -1) {
        return Promise.resolve(response.data)
      } else if (code == 203){//登录超时
        $local(appToken,null);
        $local(baseStoreState,null);
        failToast(response.data.message)
        $pathTo(process.env.VUE_APP_LOGIN as string)
      }  else {
        failToast(response.data.message)
        return Promise.reject(response.data)
      }
    } else {
      return Promise.reject(response)
    }
  },
  error => {
    closeLoading();
    const { data } = error.response || {}
    if (error.response) {
      switch (error.response.status) {
        case 404:
          failToast('网络请求不存在')
          break
        case 203://token失效
          $local(appToken,null);
          $local(baseStoreState,null);
          $pathTo(process.env.VUE_APP_LOGIN as string)
          break
        default:
          failToast(error.response.data.message)
      }
    } else {
      // 请求超时或者网络有问题
      if (error.message.includes('timeout')) {
        failToast('请求超时！请检查网络是否正常')
      } else {
        failToast('请求失败，请检查网络是否已连接')
      }
    }
    return Promise.reject(error)
  }
)

export const request = function (params,useOffline=false){
  let netState = $local(baseStoreState)?.netState;
  if(params.url.indexOf(',') == -1){
    if(params.url.indexOf('?') != -1){
      params.url = params.url+'&t='+Date.now();
    }else{
      params.url = params.url+'?t='+Date.now();
    }
  } 
  if((netState === false || useOffline) && !params.requireOnline){
    return localHttp(params).then((response:any)=>{
      const code = response.code
      if (['0','200'].indexOf(code+'') != -1) {
        return Promise.resolve(response)
      } else {
        failToast(typeof(response)!='string'?response.message:response)
        return Promise.reject(new Error((typeof(response)!='string'?response.message:response) || 'Error'))
      }
    })
  }else{
    return $axios(params)
  }  
}
